Skip to content

Conversation

@colinmurphy
Copy link
Member

@colinmurphy colinmurphy commented Mar 6, 2025

Screencast (3 mins long)

Screencast.mov

Example: Next.js App Router using the Fetch API

Table of Contents

Overview

An example headless WordPress application using Next.js App Router and the fetch API to fetch data from WordPress using WPGraphQL It showcases different data fetching strategies, state management techniques, and modern web development patterns in a real-world application context. This also contains a full example using wp-env and sample data.

Prerequisites

  • Node.js (v18+ recommended)
  • pnpm
  • Docker (if you plan on running the example see details below)

Project Structure

/
├── example-app/            # Next.js App Headless Example Application
│   ├── app/                # Application-specific pages and routes
│   ├── components/         # Reusable UI components
│   ├── lib/                # Utility functions and libraries and WP GraphQL Fragments
|
├── wp-env/                 # WordPress local environment setup
│   ├── wp-env.json
│   ├── db/                 # Example database export to be imported for the example setup
│   ├── setup/              # .htaccess file to fix a CORS issue
|   |-- screenshots/        # Example screenshots for this README
│   ├── uploads.zip         # Zipped wp-content/uploads directory for the example application
│   ├── uploads/            # Unzipped wp-content/uploads directory when the example application is run.
├── package.json            # Scripts for running the example application

Features

  • Covers various rendering patterns of Next.js

    • Server-Side Rendering (SSR) for dynamic pages
    • Static Site Generation (SSG) for static pages
    • Client-Side data fetching (CSR) for blog settings
    • Hybrid data fetching, combining SSR and CSR
  • Blog features

    • Listing posts with pagination
    • Fetching posts and pages using nodeByUri of WPGraphQL
    • Fetching static pages at build time
    • Commenting posts
    • Header with dynamic blog title
    • Featured image
    • Includes category and tag blog post listings
  • Other Template Features

    • Page template
    • CPT template with listings for a CPT events (can be adapted for other CPT)
    • Single CPT page with ACF custom meta fields

Screenshots

See screenshot directory

Running the example with wp-env

Prerequisites

Note Please make sure you have all prerequisites installed as mentioned above and Docker running (docker ps)

Setup Repository and Packages

  • Clone the repo git clone https://github.com/wpengine/hwptoolkit.git
  • Install packages `cd hwptoolkit && pnpm install
  • Setup a .env file under examples/next/client-app-router-fetch-data/example-app with "NEXT_PUBLIC_WORDPRESS_URL=http://localhost:8888
    e.g.
echo "NEXT_PUBLIC_WORDPRESS_URL=http://localhost:8888" > examples/next/client-app-router-fetch-data/example-app/.env

Build and start the application

  • cd examples/next/client-app-router-fetch-data
  • Then run pnpm example:build will build and start your application.
  • This does the following:
    • Unzips wp-env/uploads.zip to wp-env/uploads which is mapped to the wp-content/uploads directory for the Docker container.
    • Starts up wp-env
    • Imports the database from wp-env/db/database.sql
    • Install Next.js dependencies for example-app
    • Runs the Next.js dev script

Congratulations, WordPress should now be fully set up.

Frontend Admin
http://localhost:3000/ http://localhost:8888/wp-admin/

Note: The login details for the admin is username "admin" and password "password"

Command Reference

Command Description
example:build Prepares the environment by unzipping images, starting WordPress, importing the database, and starting the application.
example:dev Runs the Next.js development server.
example:dev:install Installs the required Next.js packages.
example:start Starts WordPress and the Next.js development server.
example:stop Stops the WordPress environment.
example:prune Rebuilds and restarts the application by destroying and recreating the WordPress environment.
wp:start Starts the WordPress environment.
wp:stop Stops the WordPress environment.
wp:destroy Completely removes the WordPress environment.
wp:db:query Executes a database query within the WordPress environment.
wp:db:export Exports the WordPress database to wp-env/db/database.sql.
wp:db:import Imports the WordPress database from wp-env/db/database.sql.
wp:images:unzip Extracts the WordPress uploads directory.
wp:images:zip Compresses the WordPress uploads directory.

Note You can run pnpm wp-env and use any other wp-env command. You can also see https://www.npmjs.com/package/@wordpress/env for more details on how to use or configure wp-env.

Database access

If you need database access add the following to your wp-env "phpmyadminPort": 11111, (where port 11111 is not allocated).

You can check if a port is free by running lsof -i :11111

Added scripts for wp-env to setup example fo rnext.js app. Still a bit to sort and added the start of the README.md
…ub.com:wpengine/hwptoolkit into example-data-fetch-nextjs-app-router-fetch-api
Added more posts for pagination. Added more CPT events too. Content generated by Claude.
- Restructured based on merged PRs
- Moved any wp-env assets under wp-env to make it cleaner for a developer
- Updated README.md with install
- Removed uploads directory
- Added agents.json for AI LLMs
@colinmurphy colinmurphy changed the title Initial scaffold of next.js with wp-env setup Example: Fetching data for Next.js app router using the fetch API Mar 10, 2025
Renamed template structure as per #89

Added boilerplate templates with dummy content to be filled.
Added header/footer
Fixed issue with having to flush permalinks once the DB was imported.
Fixed issue with CORS for requests from localhost:3000
Refactord all 3 templates to use the same template components
Added Posts Per Page as a variable in the next config too.
@colinmurphy colinmurphy changed the title Example: Fetching data for Next.js app router using the fetch API docs: Fetching data for Next.js app router using the fetch API Mar 13, 2025
@colinmurphy colinmurphy changed the title docs: Fetching data for Next.js app router using the fetch API docs: Example of fetching data for Next.js app router using the fetch API Mar 13, 2025
@colinmurphy
Copy link
Member Author

@josephfusco @theodesp @moonmeister @whoami-pwd @ahuseyn

The current state of this PR is:

Complete

  • WP Env setup (hopefully re-usable for other examples)
  • Homepage
  • Node By URI (Single Page and Post)
  • Blog, Category and Tag Pages (all re-use same templates)
  • Event listings (someway)

What is left to do

  • In general a bit of just testing
  • Event listings should be ordered by custom meta field data and possibly show events descending (real life would be upcoming events but this would eventually be empty)
  • Location taxonomy should be there too
  • Tidying up of the event template
  • The featured image is used 3/4 places. Should be a component
  • Single CPT for Events
  • Blog comment form and mutation
  • Documentation on caching. There is SSG, SSR, ISR
  • Update the README
  • Definitely worth going through wp-env again and making sure commands are all working

Other notes for testing

  1. http://localhost:3000/category/lifestyle is a category with a load more
  2. http://localhost:3000/mental-game-elite-athletes is a post with comments
  3. http://localhost:3000/tag/interior-design is a tag page
  4. http://localhost:3000/category/sport/marathon sub category (for checking title)

Screenshots

Screenshot 2025-03-13 at 21 16 20 Screenshot 2025-03-13 at 21 16 30 Screenshot 2025-03-13 at 21 16 44 Screenshot 2025-03-13 at 21 17 22 Screenshot 2025-03-13 at 21 17 34

- Added featured image component
- Changed WP GraphQL zip file as currently the latest release is broken
- Fixed up event listing templates
- Set version 10 for PNPM
@colinmurphy colinmurphy marked this pull request as ready for review March 21, 2025 19:13
@colinmurphy colinmurphy requested a review from a team as a code owner March 21, 2025 19:13
@colinmurphy
Copy link
Member Author

Just noting design is based off @ahuseyn example for the Next.js Pages router.

@colinmurphy colinmurphy changed the title docs: Example of fetching data for Next.js app router using the fetch API example: Fetching data for Next.js app router using the fetch API Mar 21, 2025
@colinmurphy colinmurphy changed the title example: Fetching data for Next.js app router using the fetch API feat: Client example of fetching data for Next.js app router using the fetch API Mar 21, 2025
ahuseyn
ahuseyn previously approved these changes Mar 24, 2025
Copy link
Member

@ahuseyn ahuseyn left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks amazing @colinmurphy. It became a very detailed and comprehensive example. I've followed the instructions of readme file and was just a smooth setup experience 🚀🚀🚀.

Just suggested one small typo fix from the readme.

@colinmurphy
Copy link
Member Author

Looks amazing @colinmurphy. It became a very detailed and comprehensive example. I've followed the instructions of readme file and was just a smooth setup experience 🚀🚀🚀.

Just suggested one small typo fix from the readme.

Thanks @ahuseyn ❤️ 🚀 Thanks for spending so much time reviewing and testing this. Also for your helpful feedback earlier in the PR process on the setup.

I have committed your suggestion.

@colinmurphy colinmurphy requested a review from ahuseyn March 24, 2025 15:04
Copy link
Member

@ahuseyn ahuseyn left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks amazing @colinmurphy. It became a very detailed and comprehensive example. I've followed the instructions of readme file and was just a smooth setup experience 🚀🚀🚀.
Just suggested one small typo fix from the readme.

Thanks @ahuseyn ❤️ 🚀 Thanks for spending so much time reviewing and testing this. Also for your helpful feedback earlier in the PR process on the setup.

I have committed your suggestion.

It's a pleasure, glad if I could help!

@colinmurphy colinmurphy added this pull request to the merge queue Mar 25, 2025
Merged via the queue into main with commit ad2cff9 Mar 25, 2025
1 check passed
@colinmurphy colinmurphy deleted the example-data-fetch-nextjs-app-router-fetch-api branch March 25, 2025 10:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants